package com.fallsvc.onlinemusic.controller;

import com.fallsvc.onlinemusic.mapper.UserMapper;
import com.fallsvc.onlinemusic.model.User;
import com.fallsvc.onlinemusic.service.UserService;
import com.fallsvc.onlinemusic.tools.Constant;
import com.fallsvc.onlinemusic.tools.ResponseBodyMessage;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.http.HttpRequest;

/**
 * @auther falls_vc
 * description:
 * @date 2025/3/31  11:17
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource(name = "userServiceImpl")
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login1")
    public ResponseBodyMessage<User> login1(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        User ret=userService.login(user);
        if(ret==null){
            return new ResponseBodyMessage<>(-1,"登录失败",user);
        }else{
            log.info("登录：{}",ret);
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,ret);


            return new ResponseBodyMessage<>(200,"登录成功",ret);
        }
    }
    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request){


        User ret=userService.selectUserByName(username);

        if(!bCryptPasswordEncoder.matches(password,ret.getPassword())){
            return new ResponseBodyMessage<>(-1,"登录失败",ret);
        }else{
            log.info("登录：{}",ret);

            // 防止密码泄露
            ret.setPassword("");

            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,ret);

            return new ResponseBodyMessage<>(0,"登录成功",ret);
        }
    }
}
